package org.taishan.electronshop.servlet;

import org.taishan.electronshop.dao.CustomerDao;
import org.taishan.electronshop.domain.Customer;
import org.taishan.electronshop.util.DateHelper;
import org.taishan.electronshop.util.EncryptHelper;
import org.taishan.electronshop.util.GraphicHelper;
import org.taishan.electronshop.util.StringHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

@WebServlet( "/customer/*" )
public class CustomerServlet extends HttpServlet {

    private CustomerDao customerDao = new CustomerDao();

    @Override
    protected void service(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        String uri = request.getRequestURI() ; // 从 请求对象中获取 URI
        System.out.println( "URI : " + uri  );
        /**
         * uri : /employee           ========>  firstSlash == lastSlash
         * uri : /employee/         ========>   lastSlash == length -1
         * uri : /employee/xiaowen
         * uri : /employee/hezi/qing
         */
        int firstSlash = uri.indexOf( "/" ) ; // 获得第一个 / 对应的索引
        int lastSlash = uri.lastIndexOf( "/" ) ; // 获得最后一个 / 对应的索引
        int length = uri.length() ; // 获得 字符串的长度
        int dotIndex = uri.lastIndexOf( "." ); // 从 uri 中获得最后一个 圆点的 索引

        // 如果最后一个斜杠不是第一个斜杠、并且最后一个斜杠不是最后一个字符、并且没有圆点
        if( firstSlash != lastSlash && lastSlash != length -1 && dotIndex == -1 ){
            String m = uri.substring( lastSlash + 1 ); // 截取 最后一个斜杠之后的内容
            System.out.println( "最后一个 / 之后的内容:  " + m );
            m = m.toLowerCase() ; // 全部转小写
            // JDK 1.5  之前 switch 中允许使用 byte 、short 、char、int ，从JDK 1.5 开始支持 枚举
            switch ( m ) { // Java 7 开始支持在  switch 中使用 String
                case "sign-up" :
                    signUp( request , response ) ;
                    break;
                case "sign-in" :
                    signIn( request , response ) ;
                    break;
                case "sign-out" :
                    signOut( request , response );
                    break;
                case "identify" :
                    identify( request , response );
                    break;
                default:
                    break;
            }

        }
    }

    protected void signUp(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        HttpSession session = request.getSession();

        String username = request.getParameter( "username" );

        if( StringHelper.empty( username ) ){
            session.setAttribute( "errorMessage" , "你丫用户名居然是空的"  );
            response.sendRedirect( "/sign-up.vm" );
            return ;
        }

        String password = request.getParameter( "password" );
        String name = request.getParameter( "name" );
        String address = request.getParameter( "address" );
        String telephone = request.getParameter( "telephone" );
        String birthdate = request.getParameter( "birthdate" );
        Date date = DateHelper.parseDate(birthdate);
        String identify = request.getParameter( "identify" );
        String customerIdentifyingCode = (String)session.getAttribute( "customerIdentifyingCode" );

        if( ! StringHelper.equals( customerIdentifyingCode , identify , true , true ) ){
            session.setAttribute( "errorMessage" , "验证码输入错误"  );
            response.sendRedirect( "/sign-up.vm" );
            return ;
        }

        Customer c = new Customer();
        c.setUsername( username );
        c.setPassword( password );
        c.setTelephone( telephone );
        c.setAddress(address);
        c.setName(name);
        c.setBirthdate(date);

        boolean result = customerDao.save( c );

        if( result ){
            session.setAttribute( "message" , "注册成功，可以登录了哦"  );
            response.sendRedirect( "/sign-in.vm" );
            return ;
        }

    }

    protected void signIn(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        String username = request.getParameter( "username" );
        String password = request.getParameter( "password" );

        Customer c = customerDao.load( username ) ;
        if( c == null ){
            session.setAttribute( "message" , "你输入的用户名在本系统中不存在" );
            response.sendRedirect( "/sign-in.vm" );
            return ;
        } else {
            // 先对用户输入的密码进行加密
            password = EncryptHelper.encrypt( password ) ;
            // 加密后再比较
            if( StringHelper.equals( c.getPassword() , password ) ) {
                session.setAttribute( "customer" , c  );
                session.setAttribute( "username" , username  );
                int userid = c.getId();
                session.setAttribute( "userid" , userid  );
                session.setAttribute( "password" , password  );
                response.sendRedirect( "/index.vm" );
                // request.getRequestDispatcher( "/index.vm" ).forward( request , response );
                return;
            } else {
                session.setAttribute( "username" , username );
                session.setAttribute( "message" , "你输入的密码错误" );
                response.sendRedirect( "/sign-in.vm" );
                return ;
            }

        }

    }

    protected void signOut(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        response.sendRedirect( "/index.vm" );
    }
    /*生产验证码*/
    protected void identify(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        HttpSession session = request.getSession();

        response.setContentType( "image/jpeg" );

        OutputStream out = response.getOutputStream();
        /*数量，是否为中文，宽，高，图片输出流，干扰线个数*/
        String code = GraphicHelper.create( 4 , false , 200 , 48 , out , 10 );

        session.setAttribute( "customerIdentifyingCode" , code );

    }

}
